import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { IonRange, IonSlides } from '@ionic/angular';
import { Network } from '@ionic-native/network/ngx';
import { HttpService } from 'src/app/shared/service/http.service';

@Component({
  selector: 'app-videos',
  templateUrl: './videos.component.html',
  styleUrls: ['./videos.component.scss'],
})
export class VideosComponent implements OnInit {
  @Input() tagData: any;
  @ViewChild('videos') slides: IonSlides;
  @ViewChild('range') range: IonRange;
  titleTips: any;
  index = 0;
  showVidoe = true;
  slideOpts: any;
  showGuid = false;
  video: any;
  hiddenLoading = false;
  seekbar: any;
  // progressbar: any;
  percent = 0; // 当前进度
  currentTime = "0:00"; // 当前时间
  totalTime = "0:00"; // 总时间
  showDaggerProgress = false; // 拉动进度
  hiddedMinPlayProgress = true; // 小进度
  videosData: any;
  playIconCss = `width:5rem;height: 5rem;background: url('../../../assets/fw/video_icon_suspend@3x.png') no-repeat;background-size:5rem;`;
  hivideoid: any;
  constructor(
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    public network: Network,
    public httpService: HttpService,

  ) { }

  ngOnInit() {
    this.hivideoid = "hivideo" + new Date().getTime();
    this.showGuidGif();
    if (this.tagData.data && this.tagData.data.tipTitle && this.tagData.data.tipTitle.length > 0 &&
      this.tagData.data.videos && this.tagData.data.videos.length > 0) {
      // 指定播放第几个视频

      if (this.tagData.data.currentIndex >= 0 && this.tagData.data.currentIndex < this.tagData.data.videos.length) {
        this.titleTips = this.tagData.data.tipTitle + "(" + (Number(this.tagData.data.currentIndex) + 1) + "/" +
          this.tagData.data.videos.length + ")";
        this.index = Number(this.tagData.data.currentIndex);
      } else {
        this.titleTips = this.tagData.data.tipTitle + "(1/" + this.tagData.data.videos.length + ")";
        this.index = 0;
        this.tagData.data["currentIndex"] = 0;
      }

      // 只有一个视频则不展示数量
      if (this.tagData.data.videos.length === 1) {
        this.titleTips = this.tagData.data.tipTitle;
        this.index = 0;
        this.tagData.data["currentIndex"] = 0;
      }

      this.showVidoe = true;
      this.getCurrentTitle();
      this.getIndexButtons();
      this.videosData = this.tagData.data.videos;
    }

    setTimeout(() => {

      const ele = document.querySelectorAll('video[ishivideo="true"]');
      const list: any = [];
      for (let index = 0; index < ele.length; index++) {
        const element = ele[index];
        if (element.id.indexOf(this.hivideoid) > -1) {
          list.push(element);
        }
      }
      this.video = list;
      // 如果没有播放 就开始播放吧
      if (this.video && this.video[this.index] && this.video[this.index].paused) {
        const playBtn = document.getElementById('id-playBtn' + "-" + this.hivideoid + "-" + this.index);
        playBtn.click();
      }
      const self = this;

      document.getElementById('footer-drag-progress' + "-" + this.hivideoid).addEventListener("touchend", () => {

        setTimeout(() => {
          this.showDaggerProgress = false;
        }, 800);

        const currentValue = Number(this.range.value);
        this.video[this.index].currentTime = (this.video[this.index].duration * (currentValue / 100)).toFixed(2);
      });

      document.getElementById('footer-drag-progress' + "-" + this.hivideoid).addEventListener("touchstart", () => {
        this.showDaggerProgress = true;
      });
      // 媒体数据加载完成
      this.video[0].addEventListener("loadedmetadata", () => {
        console.log('videos媒体数据加载完成~', 0);
        this.hiddedMinPlayProgress = false;
        // 如果没有播放 就开始播放吧
        if (this.video && this.video[this.index] && this.video[this.index].paused) {
          const playBtn = document.getElementById('id-playBtn' + "-" + this.hivideoid + "-" + this.index);
          playBtn.click();
          console.log('videos媒体数据加载完成~paly', 0);
          this.hiddenLoading = true;
        } else if (this.video && this.video[this.index] && !this.video[this.index].paused) {
          this.hiddenLoading = true;
        }
      });

      // video事件更新
      if (this.video && this.video[this.index]) {
        this.video[this.index].addEventListener("timeupdate", () => {
          this.hiddenLoading = true;
          this.percent = (100 / this.video[this.index].duration) * this.video[this.index].currentTime;

          const playProgressInner = document.getElementById('play-progress-inner' + "-" + this.hivideoid);
          if (playProgressInner) {
            playProgressInner.setAttribute('style', 'width:' + this.percent + '%');
          }

          if (!this.showDaggerProgress) {

            this.range.value = this.percent;

            // 更新当前时间
            this.currentTime = this.getTimeBySecond(this.video[this.index].currentTime);
            this.totalTime = this.getTimeBySecond(this.video[this.index].duration);

          }

        });

      }

    }, 200);

    setTimeout(() => {

      this.hiddedMinPlayProgress = false;
      this.totalTime = this.getTimeBySecond(this.video[this.index].duration);

      // 如果没有播放 就开始播放吧
      if (this.video && this.video[this.index] && this.video[this.index].paused) {
        const playBtn = document.getElementById('id-playBtn' + "-" + this.hivideoid + "-" + this.index);
        if (playBtn) {
          playBtn.click();
        }
        console.log('1.5S videos paly', 0);
        this.hiddenLoading = true;
      } else if (this.video && this.video[this.index] && !this.video[this.index].paused) {
        this.hiddenLoading = true;
      } else {
        setTimeout(() => {
          this.hiddenLoading = true;
        }, 1000);
      }
      this.getNetType();
      this.totalTime = this.getTimeBySecond(this.video[this.index].duration);

    }, 1500);
  }
  getNetType() {
    try {
      let wifi = true;
      const ua = window.navigator.userAgent;
      // 如果是微信
      if (/MicroMessenger/.test(ua)) {
        if (ua.indexOf('WIFI') >= 0) {
          return true;
        } else {
          wifi = false;
        }
      } else if (this.network.type !== 'none') {
        if (this.network.type !== 'wifi' &&
          this.network.type !== 'ethernet' &&
          this.network.type !== 'unknown' &&
          this.network.type !== null) {
          wifi = false;
        }
      }
      if (this.network.type === 'none') {
        this.appGlobalService.showToast('当前网络状异常,请检查网络设置~', 1500, 'middle');
      } else {
        if (!wifi) {
          this.appGlobalService.showToast('当前网络状态不是wifi，请注意流量消耗~', 1500, 'middle');
        }
      }

    } catch (e) {
      return false;
    }
  }
  // 拖动时间进度
  rangeChange(event) {
    if (this.showDaggerProgress) {
      const currentValue = event.detail.value;
      this.currentTime = this.getTimeBySecond((this.video[this.index].duration * (currentValue / 100)).toFixed(2));
    }

  }

  rangeOn(event) {
    this.showDaggerProgress = true;
  }
  rangeOff(event) {
  }
  getCurrentTitle() {
    if (this.tagData.data.videos.length === 1) {
      this.titleTips = this.tagData.data.tipTitle;
    } else {
      this.titleTips = this.tagData.data.tipTitle + "(" + Number(this.index + 1) + "/" + this.tagData.data.videos.length + ")";
    }
    return this.titleTips;
  }
  backClick(data?) {
    if (data && data.backIconLink && data.backIconLink.length > 0) {
      this.openPage(data.backIconLink[0].link);
    } else {
      this.appGlobalService.popTarget();
      this.appGlobalService.goBack();
      localStorage.removeItem('needRefresh');
    }
  }
  openPage(link) {
    // paused
    if (this.video && this.video[this.index] && !this.video[this.index].paused) {
      const playBtn = document.getElementById('id-playBtn' + "-" + this.hivideoid + "-" + this.index);
      playBtn.click();
    }
    this.pageModalService.openPage(link);
  }


  doSubmit(item) {
    const params = {
      content: item.submit.content,
      id: item.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      this.appGlobalService.showToast(res.message, 1500, "middle");
      if (res.success) {
        if (res.data && res.data.eventResult !== undefined) {
          if (res.data.eventResult === "false") {
            item.iconUrl = 'assets/icon/icon_collection_tr@3x.png';
            item.label = item.label > 0 && item.label - 1 > 0 ? Number(item.label) - 1 : '收藏';
          } else if (res.data.eventResult === "true") {
            item.iconUrl = 'assets/icon/icon_collection_color@3x.png';
            item.label = item.label > 0 ? Number(item.label) + 1 : 1;
          }
        }
      }
    });
  }


  actionClick(item) {
    if (item.type && item.type === 'sharePublish') {
      if (item.shareKey !== undefined) {
        item.link.params[item.shareKey] = this.tagData.data.videos[this.index][item.shareKey];
      }
      this.pageModalService.openPage(item.link);
    } else if (item.type && item.type === 'collectClick') {
      if (!localStorage.getItem('loginStatus')
        || (localStorage.getItem('loginStatus')
          && localStorage.getItem('loginStatus') === 'false')) {
        this.pageModalService.openPage(item.link, '', (data) => {
          this.doSubmit(item);
        });
      } else {
        this.doSubmit(item);
      }



    } else if (item.params && item.params.isLogin === 'false') {
      this.pageModalService.openPage(item.link);
    } else {
      if (item.link) {
        if (item.link.type === "pageModal") {
          const targetObj = { pageId: item.link.target, params: item.link.params, sessionId: localStorage.getItem('sessionId') };
          this.appGlobalService.targetObj = targetObj;
        }
        this.pageModalService.openPage(item.link, '', (data) => {
          item.label = data;
        });
      } else {
        this.pageModalService.openPage(item);
      }
    }

  }

  progreesAfterChange(event) {
    if (this.video) {
      console.log('progreesAfterChange to ' + event);
    }
  }
  beforeChange(event) {
    console.log('slide ' + event.from + ' to ' + event.to);
  }

  afterChange(event) {
    if ( this.tagData.data.videos.length === 1 ) {
      return;
    }
    console.log('slide to ' + event);
    this.index = Number(event);
    this.getCurrentTitle();
    this.getIndexButtons();
    this.hiddenLoading = false;
    setTimeout(() => {
      this.hiddenLoading = true;
    }, 800);

    const self = this;
    for (let i = 0; i < this.tagData.data.videos.length; i++) {
      if (i === this.index) {
        const playBtn = document.getElementById('id-playBtn' + "-" + this.hivideoid + "-" + this.index);
        playBtn.click();

        self.totalTime = this.getTimeBySecond(self.video[this.index].duration);


        // video事件更新
        if (self.video && self.video[this.index]) {
          self.video[this.index].addEventListener("timeupdate", () => {
            self.percent = (100 / self.video[this.index].duration) * self.video[this.index].currentTime;

            document.getElementById('play-progress-inner' + "-" + this.hivideoid).setAttribute('style', 'width:' + self.percent + '%');
            if (!this.showDaggerProgress) {

              this.range.value = this.percent;
              // 更新当前时间
              this.currentTime = this.getTimeBySecond(this.video[this.index].currentTime);
            }

          });

        }

      } else {
        this.video[i].pause();
        this.video[i].currentTime = 0;
      }

      if (this.tagData.data.videos.length > 1) {
        if (this.index === 0) {
          // this.appGlobalService.showToast('已经到顶了~', 1000, 'middle');

        } else if (this.tagData.data.videos.length - 1 === this.index) {
          // this.appGlobalService.showToast('已经到底了~', 1000, 'middle');

        }
      }
    }

  }

  getIndex(slides: IonSlides) {
    const that = this;
    slides.getActiveIndex().then(index => {
      that.index = index;
      console.log('index:', that.index);
      this.getCurrentTitle();
      if (that.index <= (that.tagData.data.videos.length)) {
        that.index = index;

      } else {
        that.index = 0;
      }
      const playBtn = document.getElementById('id-playBtn' + "-" + this.hivideoid + "-" + this.index);
      playBtn.click();

      if (that.tagData.data.videos.length > 1) {
        if (that.index === 0) {
          that.appGlobalService.showToast('已经到顶了~', 1500, 'middle');

        } else if (that.tagData.data.videos.length - 1 === that.index) {
          that.appGlobalService.showToast('已经到底了~', 1500, 'middle');

        }
      }
    });
  }

  /**
   * 获取time格式字符串
   */
  getTimeBySecond(second: any) {
    // tslint:disable-next-line:radix
    const hour = parseInt((second / (60 * 60)).toFixed(0));
    // tslint:disable-next-line:radix
    const minute = parseInt(((second / 60) % 60).toFixed(0));
    // tslint:disable-next-line:radix
    const subSecond = parseInt((second % 60).toFixed(0));
    // tslint:disable-next-line:max-line-length
    return (hour > 0 ? ((hour < 10 ? "0" + hour : hour) + ":") : "") + (minute < 10 ? "0" + minute : minute) + ":" + (subSecond < 10 ? "0" + subSecond : subSecond);
  }

  showGuidGif() {
    if (localStorage.getItem('hadShowGuid') === 'true') {
      this.showGuid = false;
    } else {
      if (this.tagData && this.tagData.data && this.tagData.data.videos && this.tagData.data.videos.length > 1) {
        this.showGuid = true;
        setTimeout(() => {
          this.showGuid = false;
          localStorage.setItem('hadShowGuid', 'true');
        }, 3400);
      }

    }
  }

  getIndexButtons() {
    if (this.tagData.data) {
      this.tagData.data['actionButtons'] = [];
      if (this.tagData.data.videos[this.index].collect) {
        this.tagData.data.actionButtons.push(this.tagData.data.videos[this.index].collect)
      }
      if (this.tagData.data.videos[this.index].comment) {
        this.tagData.data.actionButtons.push(this.tagData.data.videos[this.index].comment)
      }
      if (this.tagData.data.videos[this.index].share) {
        this.tagData.data.actionButtons.push(this.tagData.data.videos[this.index].share)
      }
      if (this.tagData.data.videos[this.index].call) {
        this.tagData.data.actionButtons.push(this.tagData.data.videos[this.index].call)
      }
    }
  }
}
